package com.qingke.example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HashSet<String> usernames=(HashSet<String>)request.getServletContext().getAttribute("userList");
		if(usernames==null){
			usernames=new HashSet<String>();
		}
		String username=request.getParameter("username");
		if(username==null){
			username="";
		}
		usernames.add(username);
		request.getServletContext().setAttribute("userList", usernames);
		request.getSession().setAttribute("currentUser", username);
		System.out.println("set username to session");
		System.out.println(username);
		Cookie cookie = new Cookie("loginuser",username);
		response.addCookie(cookie);
		response.sendRedirect("Chat.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
